package com.jibei.mendo;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.IBinder;
import android.support.multidex.MultiDex;

import com.jibei.mendo.bean.DaoMaster;
import com.jibei.mendo.bean.DaoSession;
import com.jibei.mendo.dao.UpgradeHelper;
import com.jibei.mendo.service.MendoService;
import com.jibei.mendo.utils.ClientUtil;
import com.jibei.mendo.utils.CrashHandler;
import com.jibei.mendo.utils.ServerUtil;
import com.jibei.mendo.utils.StatusAndNavigationBarUtil;
import com.jibei.mendo.utils.languageUtil;

import org.greenrobot.greendao.database.Database;

import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

/**
 * Created by Devin on 2019/8/11.
 */
public class MendoApplication extends Application {

    private DaoSession daoSession;
    public static MendoService mendoService;
    private static MendoApplication application;
    public static MyActivityLifecycleCallbacks myActivityLifecycleCallbacks;

    public static MendoApplication getApplication() {
        return application;
    }

    public synchronized DaoSession getDaoSession() {
        return daoSession;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @SuppressLint("CheckResult")
    @Override
    public void onCreate() {
        super.onCreate();
        //1，先发释放命令
        //2，再发配置命令
        //3，ready命令
        //4，点火命令
        //5，点火命令之后记得发释放命令

        application = this;

        StatusAndNavigationBarUtil.getInstance().showNavigationBar(this);//NavigationBar(this);
        StatusAndNavigationBarUtil.getInstance().showStatusBar(this);//StatusBar(this);

        //拉高PG9
        //GpioControl.writeGpioDirection(Constant.PG.PG9, 1);//设置PG9为输出状态
        //GpioControl.writeGpioValue(Constant.PG.PG9, 1);//拉高PG9

        //等待2秒发送释放全部的命令
        //Observable.timer(2000, TimeUnit.MILLISECONDS)
                //.subscribe(aLong -> SendCommandUtil.getInstance().sendAllReleaseCommand());

        DaoMaster.OpenHelper helper = new UpgradeHelper(this, "mendo");
        Database db = helper.getWritableDb();
        daoSession = new DaoMaster(db).newSession();

        myActivityLifecycleCallbacks = new MyActivityLifecycleCallbacks();
        registerActivityLifecycleCallbacks(myActivityLifecycleCallbacks);

        if (!BuildConfig.DEBUG) {
            CrashHandler crashHandler = CrashHandler.getInstance();
            crashHandler.init(getApplicationContext());
        }

        bindService();
        languageWork();
    }
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        languageWork();
    }

    private void languageWork() {
        Locale locale = languageUtil.getLocale(this);
        languageUtil.updateLocale(this, locale);
    }
    public void bindService() {
        bindService(new Intent(this, MendoService.class), mendoConnection, Context.BIND_AUTO_CREATE);
    }

    private ServiceConnection mendoConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mendoService = ((MendoService.MendoBinder) iBinder).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mendoService = null;
        }
    };

    @Override
    public void onTerminate() {
        super.onTerminate();
        unbindService(mendoConnection);
        ServerUtil.getInstance().disconnectServer();
        ClientUtil.getInstance().disconnectClient();
    }

    public class MyActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks {

        private List<Activity> activities = new LinkedList<>();
        public int sAnimationId = 0;

        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            addActivity(activity);
        }

        @Override
        public void onActivityStarted(Activity activity) {

        }

        @Override
        public void onActivityResumed(Activity activity) {

        }

        @Override
        public void onActivityPaused(Activity activity) {

        }

        @Override
        public void onActivityStopped(Activity activity) {

        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

        }

        @Override
        public void onActivityDestroyed(Activity activity) {
            removeActivity(activity);
        }

        /**
         * 添加Activity
         */
        public void addActivity(Activity activity) {
            if (activities == null) {
                activities = new LinkedList<>();
            }

            if (!activities.contains(activity)) {
                activities.add(activity);//把当前Activity添加到集合中
            }
        }

        /**
         * 移除Activity
         */
        public void removeActivity(Activity activity) {
            if (activities.contains(activity)) {
                activities.remove(activity);
            }

            if (activities.size() == 0) {
                activities = null;
            }
        }

        /**
         * 销毁所有activity
         */
        public void removeAllActivities() {
            for (Activity activity : activities) {
                if (null != activity) {
                    activity.finish();
                    activity.overridePendingTransition(0, sAnimationId);
                }
            }
        }
    }
}
